package ixRedis

import "github.com/garyburd/redigo/redis"

// HSet 设置哈希字段
func (c *Client) HSet(key, field string, value interface{}) error {
	conn, err := c.getConn()
	if err != nil {
		return err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	_, err = conn.Do("HSET", fullKey, field, value)
	return err
}

// HGet 获取哈希字段
func (c *Client) HGet(key, field string) (string, error) {
	conn, err := c.getConn()
	if err != nil {
		return "", err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	reply, err := redis.String(conn.Do("HGET", fullKey, field))
	if err == redis.ErrNil {
		return "", nil
	}
	return reply, err
}

// HGetAll 获取哈希所有字段
func (c *Client) HGetAll(key string) (map[string]string, error) {
	conn, err := c.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.StringMap(conn.Do("HGETALL", fullKey))
}

// HDel 删除哈希字段
func (c *Client) HDel(key string, fields ...string) (int64, error) {
	if len(fields) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(fields)+1)
	args[0] = fullKey
	for i, field := range fields {
		args[i+1] = field
	}

	return redis.Int64(conn.Do("HDEL", args...))
}

// HExists 检查哈希字段是否存在
func (c *Client) HExists(key, field string) (bool, error) {
	conn, err := c.getConn()
	if err != nil {
		return false, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	count, err := redis.Int64(conn.Do("HEXISTS", fullKey, field))
	return count > 0, err
}
